package com.zoe.app.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.zoe.app.annotation.DataSource;
import com.zoe.app.dynamic.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/**
 * @author zoe.Zhang
 * @date 2023/02/24
 * @description
 */
@EnableAspectJAutoProxy(exposeProxy = true)
@Aspect
@Component
public class DataSourceAspect {
    @Around(value = "@annotation(dataSource)")
    public Object around(ProceedingJoinPoint point, DataSource dataSource) {
        if (!ObjectUtil.isNull(dataSource)) {
            String dataSourceValue = dataSource.value();
            DynamicDataSourceContextHolder.setDataSource(dataSourceValue);
        }
        try {
            return point.proceed();
        }
        catch (Throwable e) {
            throw new RuntimeException(e);
        }
        finally {
            DynamicDataSourceContextHolder.clearDataSource();
        }
    }
}
